<script lang="jsx">
import {delivery_range_map, landing_type_map} from "./other/tt/enumerate";
import cityInitial from './other/city-initial.json'
import {
  android_osv_type,
  device_brand_lists,
  equipment_price_lists,
  filter_converted_level_type,
  gender_type,
  ios_osv_type,
  network_type,
  optional_age,
  platform_os_type,
  user_type_lists
} from './other/ks/enumerate'
import {
  getAudienceName
} from '@/api/ks/crowd-pack'
import {
  getTargetTagsDto
} from '@/api/ks/target'

function mapToObject(data) {
  return [...data.entries()].reduce((obj, [key, value]) => {
    obj[value] = key
    return obj
  }, {})
}

const genderType = mapToObject(gender_type)
const optionalAge = mapToObject(optional_age)
const platFormOsType = mapToObject(platform_os_type)
const androidOsvType = mapToObject(android_osv_type)
const iosOsvType = mapToObject(ios_osv_type)
const deviceBrandLists = mapToObject(device_brand_lists)
const equipmentPriceLists = mapToObject(equipment_price_lists)
const networkType = mapToObject(network_type)
const userTypeLists = mapToObject(user_type_lists)
const filterConvertedLevelType = mapToObject(filter_converted_level_type)
// 行为场景
const sceneType = {
  1: '社区',
  2: 'APP',
  3: '电商',
  4: '推广',
}
const timeType = {
  0: '最近7天',
  1: '最近15天',
  2: '最近30天',
  3: '最近90天',
  4: '最近180天',
}

// 根据某个标识获取某条数据
function recursionFindObj(data, id) {
  let result = null;
  if (!data.length) {
    return;
  }
  for (let i of data) {
    // 已经找到了属性值所在的对象就终止循环,以免后面的循环覆盖result,导致出错
    if (!!result) break;
    if (+i.id === +id) {
      result = i;
      break
    } else if (i.subclass_indicator) {
      result = recursionFindObj(i.subclass_indicator, id);
    }
  }
  return result;
}

export default {
  name: 'targetContentDetail',
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    isShowName: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      // 定向人群包中文
      retargetingIncludeNameMap: [],
      // 排除人群包中文
      retargetingExcludeNameMap: [],
      // 商业兴趣中文
      businessInterestNameMap: [],
    }
  },
  render() {
    return (
      <div className="t_target_detail">
        {
          this.isShowName && <div className="t_target_detail_item">
            <div className="label">定向包名称：</div>
            <div className="content">{this.data.template_name}</div>
          </div>
        }
        {
          this.isShowName && <div className="t_target_detail_item">
            <div className="label">企业名称：</div>
            <div className="content">{this.data.advertiser_subject_name}</div>
          </div>
        }
        {
          this.isShowName && <div className="t_target_detail_item">
            <div className="label">项目：</div>
            <div className="content">{this.data.project_name}</div>
          </div>
        }
        {
          this.data?.region.length > 0 && (
            <div className="t_target_detail_item">
              <div className="label">地域：</div>
              <div className="content">
                {
                  this.data?.region.map(item => cityInitial[item].full_name.replace(/中国./, ''))
                    .join('、')
                }
              </div>
            </div>
          )
        }
        {
          Boolean(this.data?.gender) && (
            <div className="t_target_detail_item">
              <div className="label">性别：</div>
              <div className="content">
                {genderType[this.data?.gender]}
              </div>
            </div>
          )
        }
        {
          (!!Object.keys(this?.data?.age).length || !!this?.data?.ages_range.length) &&
          (<div className="t_target_detail_item">
            <div className="label">年龄：</div>
            <div className="content">
              {
                Object.keys(this?.data?.age).length > 0 &&
                `${this?.data?.age.min}-${this?.data?.age.max}`
              }
              {
                this?.data?.ages_range.length > 0 &&
                this?.data?.ages_range.map(item => optionalAge[item]).join('、')
              }
            </div>
          </div>)
        }
        {
          this?.data?.population.length > 0 && (
            <div className="t_target_detail_item">
              <div className="label">定向人群包：</div>
              <div className="content">
                {this.retargetingIncludeNameMap.join('、')}
                {/*this?.data?.population.join('、')*/}
              </div>
            </div>
          )
        }
        {
          this?.data?.exclude_population.length > 0 && (
            <div className="t_target_detail_item">
              <div className="label">排除人群包：</div>
              <div className="content">
                {this.retargetingExcludeNameMap.join('、')}
                {/*this?.data?.exclude_population.join('、')*/}
              </div>
            </div>
          )
        }
        {
          this?.data?.platform_os !== undefined && (
            <div className="t_target_detail_item">
              <div className="label">平台：</div>
              <div className="content">
                {platFormOsType[this?.data?.platform_os]}
              </div>
            </div>
          )
        }
        {
          Boolean((this?.data.android_osv && +this?.data.android_osv !== 3) ||
            (+this?.data.ios_osv && +this?.data.ios_osv !== 6)) && (
            <div className="t_target_detail_item">
              <div className="label">{this?.data.android_osv ? '安卓' : 'IOS'}版本：</div>
              <div className="content">
                {
                  this?.data.android_osv ?
                    androidOsvType[this?.data.android_osv] :
                    iosOsvType[this?.data.ios_osv]
                }
              </div>
            </div>
          )
        }
        {
          this?.data?.device_brand.length > 0 && (
            <div className="t_target_detail_item">
              <div className="label">手机品牌：</div>
              <div className="content">
                {this?.data.device_brand.map(item => deviceBrandLists[item]).join('、')}
              </div>
            </div>
          )
        }
        {
          this?.data?.device_price.length > 0 && (
            <div className="t_target_detail_item">
              <div className="label">设备价格：</div>
              <div className="content">
                {this?.data.device_price.map(item => equipmentPriceLists[item]).join('、')}
              </div>
            </div>
          )
        }
        {
          Boolean(this?.data?.network) && (
            <div className="t_target_detail_item">
              <div className="label">网络环境：</div>
              <div className="content">
                {networkType[this?.data.network]}
              </div>
            </div>
          )
        }
        {
          [0, 1].includes(this?.data.user_type) && (
            <div className="t_target_detail_item">
              <div className="label">用户类型：</div>
              <div className="content">
                {userTypeLists[this?.data.user_type]}
              </div>
            </div>
          )
        }
        {
          Boolean(this?.data.business_interest_type) && (
            <div className="t_target_detail_item">
              <div className="label">商业兴趣：</div>
              <div className="content">
                {/*
                  this?.data.business_interest_type === 1 ?
                    '智能推荐' :
                    this?.data.business_interest.join('、')
                */}
                {
                  this?.data.business_interest_type === 1 ?
                    '智能推荐' :
                    this.businessInterestNameMap.join('、')
                }
              </div>
            </div>
          )
        }
        {
          this?.data.celebrity?.fans_stars?.length > 0 && (
            <div className="t_target_detail_item">
              <div className="label">网红粉丝：</div>
              <div className="content">
                {this?.data?.celebrity?.fans_stars?.map(item => item.name).join('、')}
              </div>
            </div>
          )
        }
        {
          this?.data?.behavior_interest?.behavior?.scene_type?.length > 0 && (
            <div className="t_target_detail_item">
              <div className="label">行为场景：</div>
              <div className="content">
                {this?.data?.behavior_interest?.behavior?.scene_type?.map(item => sceneType[item]).join('、')}
              </div>
            </div>
          )
        }
        {
          Boolean(this?.data?.behavior_interest?.behavior?.time_type) && (
            <div className="t_target_detail_item">
              <div className="label">行为天数：</div>
              <div className="content">
                {timeType[this?.data.behavior_interest.behavior.time_type]}
              </div>
            </div>
          )
        }
        {
          Boolean(this?.data?.behavior_interest?.behavior?.strength_type) && (
            <div className="t_target_detail_item">
              <div className="label">行为强度：</div>
              <div className="content">
                高强度
              </div>
            </div>
          )
        }
        {
          Boolean(this?.data?.filter_converted_level) && (
            <div className="t_target_detail_item">
              <div className="label">过滤已转化用户：</div>
              <div className="content">
                {filterConvertedLevelType[this?.data.filter_converted_level]}
              </div>
            </div>
          )
        }
        {
          Boolean(this?.data?.intelli_extend.is_open) && (
            <div className="t_target_detail_item">
              <div className="label">智能扩量：</div>
              <div className="content">
                {
                  this?.data.intelli_extend.no_age_break ?
                    `不可突破年龄${this?.data.intelli_extend.no_gender_break ? '、' : ''}` : null
                }
                {
                  this?.data.intelli_extend.no_gender_break ?
                    `不可突破性别${this?.data.intelli_extend.no_area_break ? '、' : ''}` : null
                }
                {this?.data.intelli_extend.no_area_break ? '不可突破地域' : null}
              </div>
            </div>
          )
        }
      </div>
    )
  },
  methods: {
    async getBusinessInterest() {
      if (!this.data.business_interest.length) return
      let params = {
        type: 'BUSINESS_INTEREST',
      }
      if (this.data.advertiser_id) {
        params.advertiser_id = this.data.advertiser_id
      } else if (this.data.advertiser_subject_name) {
        params.advertiser_subject_name = this.data.advertiser_subject_name
      }
      let {data, code} = await getTargetTagsDto(params).catch(e => e)
      if (code !== 0) data = [];
      this.businessInterestNameMap = this.data.business_interest.map(item => {
        let val = recursionFindObj(data, item)
        return val ? `${val.id}(${val.name})` : `${item}(获取名称失败)`
      })
    },
    // 执行获取人群中文数据
    getCrowd() {
      // 定向人群包
      let includeIds = this.data?.population
      // 排除人群包
      let excludeIds = this.data?.exclude_population
      if (includeIds.length) {
        this.asyncGetAudienceName({
          mark: true,
          params: {
            advertiser_id: this.data?.advertiser_id,
            audience_ids: includeIds,
          }
        })
      }
      if (excludeIds.length) {
        this.asyncGetAudienceName({
          mark: false,
          params: {
            advertiser_id: this.data?.advertiser_id,
            audience_ids: excludeIds,
          }
        })
      }
    },
    // 获取定向人群包对应中文
    async asyncGetAudienceName({mark, params}) {
      let {data} = await getAudienceName(params)
      // true 定向人群包  false 排除人群包
      if (mark) {
        this.retargetingIncludeNameMap = data
      } else {
        this.retargetingExcludeNameMap = data
      }
    }
  },
  mounted() {
    if (!Object.keys(this.data).length) return
    this.getCrowd()
    this.getBusinessInterest()
  }
}
</script>

<style lang="scss">
.t_target_detail {
  width: 360px;
  height: 360px;
  padding: 12px;
  overflow: auto;

  .t_target_detail_item {
    display: flex;
    flex-wrap: nowrap;
    font-size: 12px;
    margin-bottom: 10px;

    .label {
      width: 96px;
      text-align: right;
      color: $h3-text-color;
      flex-shrink: 0;
    }

    .content {
      flex-grow: 1;
      line-height: 16px;
      color: $h1-text-color;
      white-space: normal;
      word-wrap: break-word;
      word-break: break-all;
    }
  }
}
</style>
